package com.force.common.h2.service;

import com.force.common.h2.models.H2JdbcTemplate;
import com.force.common.h2.models.ZincLogVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class H2TemplateService {



	@Autowired
	H2JdbcTemplate h2JdbcTemplate;
	public List<Map<String, Object>> getLogList(ZincLogVo vo){

		// Default to query logs from the last 2 hours
		LocalDateTime now = LocalDateTime.now();
		LocalDateTime twoHoursAgo = now.minusHours(2);
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String defaultStartTimeStamp = twoHoursAgo.format(formatter);
		String defaultEndTimeStamp = now.format(formatter);


		StringBuilder sql = new StringBuilder("SELECT group_name, thread_name, logger_name, content, level, throwable_msg, trace_id, client_ip, timestamp FROM LOGS WHERE 1=1");
		List<Object> params = new ArrayList<>();

		if (vo != null && StringUtils.isNotEmpty(vo.getGroupName())) {
			sql.append(" AND group_name = ?");
			params.add(vo.getGroupName());
		}
		if (vo != null && StringUtils.isNotEmpty(vo.getThreadName())) {
			sql.append(" AND thread_name = ?");
			params.add(vo.getThreadName());
		}
		if (vo != null && StringUtils.isNotEmpty(vo.getLoggerName())) {
			sql.append(" AND logger_name = ?");
			params.add(vo.getLoggerName());
		}
		if (vo != null &&  StringUtils.isNotEmpty(vo.getContent())) {
			sql.append(" AND content = ?");
			params.add(vo.getContent());
		}
		if (vo != null && StringUtils.isNotEmpty(vo.getLevel())) {
			sql.append(" AND level = ?");
			params.add(vo.getLevel());
		}
		if (vo != null && StringUtils.isNotEmpty(vo.getThrowableMsg())) {
			sql.append(" AND throwable_msg = ?");
			params.add(vo.getThrowableMsg());
		}
		if (vo != null && StringUtils.isNotEmpty(vo.getTraceId())) {
			sql.append(" AND trace_id = ?");
			params.add(vo.getTraceId());
		}
		if (vo != null && StringUtils.isNotEmpty(vo.getClientIp())) {
			sql.append(" AND client_ip = ?");
			params.add(vo.getClientIp());
		}
		if (vo != null&&StringUtils.isNotEmpty(vo.getStartTimeStamp())) {
			sql.append(" AND timestamp >= ?");
			params.add(vo.getStartTimeStamp());
		}else {
			sql.append(" AND timestamp >= ?");
			params.add(defaultStartTimeStamp);
		}
		if (vo != null&&StringUtils.isNotEmpty(vo.getEndTimeStamp())) {
			sql.append(" AND timestamp <= ?");
			params.add(vo.getEndTimeStamp());
		}else {
			sql.append(" AND timestamp <= ?");
			params.add(defaultEndTimeStamp);
		}

		sql.append(" order by timestamp desc");
		return h2JdbcTemplate.queryForList(sql.toString(), params.toArray());
	}

}
